<template>
  <div style="width: 1300px" class="purchase-order-form-container">
    <h3 class="form-title">新增采购单</h3>
    <el-form :model="form" class="form-wrapper">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="采购单号">
            <el-input
              disabled
              v-model="form.purchaseOrderNumber"
              placeholder="可不填写，自动生成"
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据类型" required>
            <el-select
              v-model="form.billType"
              placeholder="请选择入库类别"
              class="form-select"
            >
              <el-option label="正常入库" value="正常入库"></el-option>
              <el-option label="等待入库" value="等待入库"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联订单号">
            <el-input
              disabled
              placeholder="请输入关联订单号"
              v-model="form.associatedorderNumber"
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="供应商名">
            <el-input
              v-model="form.supplierName"
              placeholder=""
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名称">
            <el-input
              v-model="form.customerName"
              placeholder=""
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人">
            <el-input
              v-model="form.contactPerson"
              placeholder=""
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="电话">
            <el-input
              v-model="form.phone"
              placeholder=""
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货日">
            <el-date-picker
              v-model="form.receiveDate"
              type="date"
              placeholder="选择日期"
              class="form-datepicker"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入备注信息"
              class="form-textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="制单人">
            <el-input
              v-model="form.maker"
              placeholder=""
              disabled
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单时间">
            <el-input
              v-model="form.makeTime"
              placeholder=""
              disabled
              class="form-input"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="productList" border class="product-table">
      <el-table-column label="产品编码" prop="productId"></el-table-column>
      <el-table-column label="产品名称" prop="productName"></el-table-column>
      <el-table-column label="规格" prop="specification"></el-table-column>
      <el-table-column label="类别" prop="category"></el-table-column>
      <el-table-column label="存储单位" prop="unitId"></el-table-column>
      <el-table-column label="单价" prop="price"></el-table-column>
      <el-table-column label="数量">
        <template #default="scope">
          <el-input
            v-model="scope.row.quantity"
            placeholder="输入数量"
            class="table-input"
            @input="calculateTotal(scope.row)"
          ></el-input>
        </template>
      </el-table-column>
      <!-- 新增批次列，可根据实际需求决定是否展示/编辑 -->
      <el-table-column label="批次">
        <template #default="scope">
          <el-input
            disabled
            v-model="scope.row.batch"
            placeholder="可不填写，自动生成"
            class="table-input"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="总价" prop="totalPrice"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="text"
            @click="deleteProduct(scope.row)"
            class="table-ops-button"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="button-group">
      <el-button
        type="primary"
        @click="openProductSelector"
        class="action-button"
        >新增产品</el-button
      >
      <el-button type="primary" @click="submitForm" class="action-button"
        >提交</el-button
      >
      <el-button @click="cancelForm" class="action-button">取消</el-button>
    </div>
  </div>
  <el-dialog
    title="选择产品"
    ref="dialogRef"
    v-model="dialogVisible"
    width="1200px"
  >
    <el-form :model="searchParams" class="search-form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品编号">
            <el-input
              v-model="searchParams.productId"
              placeholder="请输入编码"
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称">
            <el-input
              v-model="searchParams.productName"
              placeholder="请输入名称"
              class="form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="search-button-container">
      <el-button type="primary" @click="searchProducts" class="search-button">
        搜索
      </el-button>
    </div>
    <el-table
      @selection-change="handleSelectionChange"
      :data="dialogProductList"
      border
      class="product-table"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="产品编码" prop="productId"></el-table-column>
      <el-table-column label="产品名称" prop="productName"></el-table-column>
      <el-table-column label="规格" prop="specification"></el-table-column>
      <el-table-column label="类别" prop="category"></el-table-column>
      <el-table-column label="存储单位" prop="unitId"></el-table-column>
      <el-table-column label="单价" prop="price"></el-table-column>
      <el-table-column label="显示名" prop="description"></el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="form1.PageIndex"
      v-model:page-size="form1.PageSize"
      :page-sizes="[1, 3, 15, 100]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="form1.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <br />
    <div class="button-group">
      <el-button @click="closeDialog" class="action-button"> 关闭 </el-button>
      <el-button type="primary" @click="confirmSelection" class="action-button">
        选择
      </el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { KongaUrl } from "@/axios/axiosHelp";
const router = useRouter();
const ApiEnums = {
  成功: 0,
  失败: 1,
};

const form = ref({
  command: "111",
  purchaseOrderNumber: "",
  associatedorderNumber: "",
  billType: "",
  supplierName: "",
  customerName: "",
  contactPerson: "",
  phone: "",
  receiveDate: "",
  remark: "",
  maker: "张鹏",
  makeTime: "2019-05-25",
});

const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});
const handleSizeChange = (newSize) => {
  form1.PageSize = newSize;
  searchProducts();
};

const handleCurrentChange = (newPage) => {
  form1.PageIndex = newPage;
  searchProducts();
};
const productList = ref([]);
const dialogProductList = ref([]);

const searchParams = ref({
  productCode: "",
  productName: "",
});
const dialogVisible = ref(false);
const openProductSelector = () => {
  dialogVisible.value = true;
  searchProducts();
};

const searchProducts = () => {
  KongaUrl
    .get("/wangcong/api/Whouase/GetProductModels", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      dialogProductList.value = res.data.data.list;
      form1.TotalCount = res.data.data.totalCount;
      form1.PageCount = res.data.data.PageCount;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};

const deleteProduct = (product) => {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = productList.value.indexOf(product);
      if (index !== -1) {
        productList.value.splice(index, 1);
      }
    })
    .catch(() => {});
};

const dialogSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  dialogSelection.value = val;
};

const confirmSelection = () => {
  const selectedRows = dialogSelection.value;
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }
  selectedRows.forEach((selectedProduct) => {
    productList.value.push({
      productName: selectedProduct.productName,
      productId: selectedProduct.productId,
      category: selectedProduct.category,
      specification: selectedProduct.specification,
      unitId: selectedProduct.unitId,
      price: selectedProduct.price,
      quantity: "",
      batch: "", // 初始化批次为空
      totalPrice: "",
    });
  });
  closeDialog();
};

const closeDialog = () => {
  dialogVisible.value = false;
  searchParams.value.productCode = "";
  searchParams.value.productName = "";
  dialogProductList.value.forEach((row) => {
    row._checked = false;
  });
};

const submitForm = async () => {
  try {
    const requestData = {
      ...form.value,
      Products: productList.value.map((item) => ({
        ProductId: item.productId,
        Quantity: item.quantity,
        Batch: item.batch, // 使用表格中输入的批次
        UnitPrice: item.price,
      })),
    };
    KongaUrl
      .post("/wangcong1/api/WHouase/AddPurchaseOrder", requestData)
      .then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
          router.push("/GetPurchasing");
        } else {
          ElMessage.error(res.data.message);
        }
      });
  } catch (error) {
    console.error("提交表单失败", error);
    ElMessage.error("提交过程中发生错误，请检查网络或联系管理员");
  }
};

const cancelForm = () => {
  console.log("取消表单");
};

const calculateTotal = (row: any) => {
  if (row.quantity !== "" && row.price !== "") {
    row.totalPrice = (Number(row.quantity) * Number(row.price)).toFixed(2);
  } else {
    row.totalPrice = "";
  }
};
const generateTwelveDigitNumber = () => {
  const characters = "0123456789";
  let result = "";
  for (let i = 0; i < 12; i++) {
    // 生成12位数字
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};

onMounted(() => {
  form.value.purchaseOrderNumber = generateTwelveDigitNumber();
  form.value.associatedorderNumber = generateTwelveDigitNumber();
});
</script>


<style scoped>
.purchase-order-form-container {
  width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.form-title {
  text-align: center;
  margin-bottom: 20px;
}

.form-wrapper {
  margin-bottom: 20px;
}

/* 统一表单输入框样式和宽度 */
.form-input,
.form-select,
.form-datepicker,
.form-textarea {
  width: 240px; /* 统一设置宽度 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px 12px;
  transition: border-color 0.2s ease;
}

.form-textarea {
  height: 80px;
}

.product-table {
  width: 100%;
  margin-bottom: 20px;
}

.table-input {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 6px 10px;
  transition: border-color 0.2s ease;
}

.table-ops-button {
  color: #409eff;
  transition: color 0.2s ease;
}

.table-ops-button:hover {
  color: #66b1ff;
}

.button-group {
  text-align: center;
  display: flex;
  justify-content: space-around;
}

.action-button {
  margin: 0 10px;
}

.el-row {
  margin-bottom: 20px;
  display: flex; /* 使用flex布局优化对齐 */
  flex-wrap: wrap;
}

.el-col {
  flex: 0 0 33.333333%; /* 平均分布列，可根据实际调整 */
  max-width: 33.333333%;
  margin-bottom: 15px; /* 增加间距让布局更整洁 */
}

.el-form-item {
  label-width: 120px;
  font-size: 16px;
  color: #333;
}

.search-form {
  margin-bottom: 20px;
}

.search-button-container {
  margin-bottom: 10px;
}

.search-button {
  padding: 8px 16px;
}

.product-table {
  width: 100%;
  margin-bottom: 10px;
}

.pagination {
  margin-bottom: 10px;
  text-align: center;
}

.button-group {
  text-align: right;
}
</style>